<template>
  <div>
    <!--搜索 -->
    <div style="display: flex; justify-content: flex-end">
      <el-form :model="queryParams" class="filter-form-inline" label-position="right" size="small">
        <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="产品信息" style="width:300px;margin-right:20px;">
            <el-select v-model="queryParams.productId" clearable placeholder="请选择产品" @change="handlChangeProduct">
              <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
                :value="item.productId" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <filter-popover :form-list="formList" right="20px" @onConfirm="filterDataConfirm" @onReset="filterReset" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!--表格-->
    <table-view :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header" size="medium"
      @row-click="aloneClick">
      <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="产品通用名"
        prop="productPopularName">
        <template #default="{row}">
          <span class="main-color">{{ row.productPopularName }}</span>
        </template>
      </el-table-column>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="商品名"
        prop="productName" />

      <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="生产厂家"
        prop="producer" />

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" fixed="left" label="准入模式">
        <template #default="{row}">
          {{ getLabel('access_mode', row.accessMode) }}
        </template>
      </el-table-column>

      <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" label="终端价(元)"
        prop="terminalPrice">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.terminalPrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="交易价(元)" prop="tradePrice">
        <template #default="{row}">
          <div style="text-align: right">
            {{ isInteger(row.tradePrice) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="营销模式">
        <template #default="{row}">

          <span v-if="row.sellMode !== 'direct'">
            {{ row.agentAttribute === '1' ? '区域招商' : '精细招商' }}
          </span>
          <span v-else> 终端直销</span>
        </template>
      </el-table-column>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="代理名称"
        prop="agentName">
        <template #default="{row}">
          <span v-if="row.agentType === 'agent'" class="main-color">{{ row.agentName }}</span>
          <span v-if="row.agentType === 'agent_person'" class="main-color">{{ row?.agentDetail?.userName }}</span>
        </template>
      </el-table-column>

      <el-table-column :min-width="160" :show-overflow-tooltip="true" align="center" label="配送商">
        <template #default="{row}">
          <distributors-view v-if="row.distributeContractDetails && row.distributeContractDetails.length" :boole="false"
            :booleType="false" :datas="row.distributeContractDetails" :unit="row.productInfoDetail?.sellUnit" />
        </template>
      </el-table-column>

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="负责营销职员" prop="headName" />

      <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" fixed="right" label="开发期限截至"
        prop="terminalStatus">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd", row.expireTime) }}
        </template>
      </el-table-column>

      <!-- <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" fixed="right" label="注册日期"
        prop="terminalStatus">
        <template #default="{row}">
          {{ dateFormat("yyyy-mm-dd", row.agentRegisterTime) }}
        </template>
      </el-table-column> -->

      <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" fixed="right" label="状态">
        <template #default="{row}">
          <div v-if="row.flowStatus !=='DOING'">
            {{ getLabel('fine_terminal', row.devStatus) }}
          </div>
          <div v-if="row.flowStatus ==='DOING'">{{ getLabel('approval_result', row.flowStatus) }}
          </div>
        </template>
      </el-table-column>
    </table-view>
    <!--页码-->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.page" :total="total"
      style="display: flex; justify-content: flex-end" @pagination="handlList" />
    <!--编辑终端-->
    <registered ref="registeredDialog" />
    <!--设置配送信息-->
    <setiDelivery ref="setiDeliveryDialog" @distributeSuccsess="distributeSuccsess" />
    <!-- 开发中产品详情 -->
    <detail-drawer ref="detailDrawer" :size-width="1000" custom-title>
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div style="width: 70%">
            <span style="padding-right: 15px">{{ formData?.terminalName }} </span>
            <el-tag v-if="productData.flowStatus!=='DOING'" size="small" type="warning">
              {{ getLabel('fine_terminal', productData.devStatus) }}
            </el-tag>
            <el-tag v-if="productData.flowStatus ==='DOING'" size="small" style="margin-left: 15px" type="warning">
              {{ getLabel('approval_result', productData.flowStatus) }}
            </el-tag>
          </div>
        </div>

      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <product-detail ref="productDetailDrawer" :product-id="productData.id" />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--产品详情-->
    <detail-drawer ref="proDetailDrawer" custom-title>
      <template #title>
        {{ getProductName(productData?.productInfoDetail) }}
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <product-base-info v-if="productData.productId" :id="productData.productId" />
          </div>
          <div class="history-list">
            <item-title title="修改记录" />
            <operation-view :id="productData.id" mode="product" />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--代理商详情-->
    <detail-drawer ref="agentRef" custom-title>
      <template #title>
        <span v-if="productData.agentType === 'agent'">{{ productData.agentName }}</span>
        <span v-if="productData.agentType === 'agent_person'">{{ productData?.agentDetail?.userName }}</span>
      </template>
      <template #contents>
        <agentInfo :id="productData.agentId" />
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute } from "vue-router";
import { crmStore } from "@CRM/store";

export default {
  name: "Product",
  components: {
    setiDelivery: defineAsyncComponent(() => import("./setiDelivery.vue")),
    productDetail: defineAsyncComponent(() => import("./productDetail.vue")),
    registered: defineAsyncComponent(() => import("./registered.vue")),
    productBaseInfo: defineAsyncComponent(() =>
      import(
        "@CRM/views/commonView/detailComponents/product/productBaseInfo.vue"
      )
    ),
    agentInfo: defineAsyncComponent(() =>
      import("@CRM/views/commonView/detailComponents/agent/agentInfo")
    ),
  },
  props: {
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  setup(props, context) {
    const api = inject("api");
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const handleArray = (str) => {
      let arr = crmStore.getters["dictionary/getDictionary"][str] || [];
      return arr;
    };
    var data = reactive({
      tableData: [],
      setiDeliveryDialog: null,
      detailDrawer: null,
      productDetailDrawer: null,
      queryParams: {
        pageSize: 20,
        page: 1,
        terminalId: Number(route.query.id),
        productId: null,
        devStatus: "",
        terminalListType: "",
        agentName: "",
        distributeName: "",
        registerStartTime: null,
        registerEndTime: null,
        expireTimeStartTime: null,
        expireTimeEndTime: null,
        productDownListType: "5",
      },
      total: 0,
      registeredDialog: null,
      productData: null,
      proDetailDrawer: null,
      agentRef: null,
      productList: [],
      formList: [
        {
          key: "devStatus",
          label: "状态",
          form_type: "select",
          value: "",
          is_search: false,
          options: handleArray("fine_terminal").filter(
            (a) =>
              a.value === "2" ||
              a.value === "4" ||
              a.value === "-2" ||
              a.value === "-8"
          ),
        },
        {
          key: "terminalListType",
          label: "营销模式",
          form_type: "select",
          value: "",
          is_search: false,
          options: [
            {label:'精细招商',value:'1'},
            {label:'直销终端',value:'2'},
            {label:'区域招商',value:'3'},
            ],
        },
        {
          key: "agentName",
          label: "代理名称",
          form_type: "text",
          value: "",
          is_search: false,
          options: [],
        },
        {
          key: "distributeName",
          label: "配送商名称",
          form_type: "text",
          value: "",
          is_search: false,
          options: [],
        },
        {
          key: "date_range1",
          label: "注册日期",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: "date_range2",
          label: "开发截止日期",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
      ],
    });

    // 获取产品下拉
    const handlProductData = async () => {
      const res = await api.terminal.TERMINAL_PRODUCTID({
        terminalId: Number(route.query.id),
      });
      if (res.code === 0) {
        data.productList = res.data;
      }
    };

    // 产品事件
    const handlChangeProduct = (val) => {
      if (val) {
        data.queryParams.productId = val;
      } else {
        data.queryParams.productId = 0;
      }
      data.queryParams.page = 1;
      handlList();
    };

    // 获取列表
    const handlList = () => {
      api.terminal.PRODUCT_LIST(data.queryParams).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 确定搜所
    const filterDataConfirm = (val) => {
      data.queryParams.devStatus = val.devStatus;
      data.queryParams.terminalListType = val.terminalListType;
      data.queryParams.agentName = val.agentName;
      data.queryParams.distributeName = val.distributeName;
      data.queryParams.registerStartTime = val.date_range1[0];
      data.queryParams.registerEndTime = val.date_range1[1];
      data.queryParams.expireTimeStartTime = val.date_range2[0];
      data.queryParams.expireTimeEndTime = val.date_range2[1];
      data.queryParams.page = 1;
      handlList();
    };

    // 取消
    const filterReset = () => {
      data.queryParams = {
        pageSize: 20,
        page: 1,
        terminalId: Number(route.query.id),
        productId: "",
        devStatus: "",
        terminalListType: "",
        agentName: "",
        distributeName: "",
        registerStartTime: null,
        registerEndTime: null,
        expireTimeStartTime: null,
        expireTimeEndTime: null,
        productDownListType: "5",
      };
      handlList();
    };

    // 编辑
    const handlEdit = (row) => {
      data.registeredDialog.open(props.formData, row);
    };

    // 删除
    const handlDele = (id, num) => {
      currentInstance.proxy
        .alertBox({
          message: "删除数据后不可恢复,确定删除？",
        })
        .then(() => {
          api.terminal.REGISTERED_DELETE(id).then((res) => {
            if (res.code === 0) {
              if (num === 2) {
                data.detailDrawer.close();
              } else {
                handlList();
              }
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    // 设置配送信息
    const handlSet = (val) => {
      data.setiDeliveryDialog.open(val, val.id);
    };

    const handlFailure = (row, num) => {
      currentInstance.proxy
        .alertBox({
          message: "确认更改该终端产品状态为开发失败？",
        })
        .then(() => {
          api.terminal.TERMINAL_FAILURE(row.id).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            } else {
              if (num === 2) {
                data.productDetailDrawer.handlDetail();
              } else {
                handlList();
              }
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const aloneClick = (row, column, event) => {
      data.productData = row;
      if (column.label === "产品通用名") {
        data.proDetailDrawer.open();
        return;
      }
      if (column.label === "代理名称") {
        if (row.sellMode !== "direct") {
          data.agentRef.open();
        }
        return;
      }
      if (column.label === "操作") {
        return;
      }
      data.detailDrawer.open();
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    };

    const distributeSuccsess = () => {
      handlList();
    };

    const handlCalculate = (val) => {
      let a = "";
      let conut = 0;
      if (val.length > 0 && val.length === 1) {
        a = val[0].distributeName;
      } else {
        for (let i = 0; i < val.length; i++) {
          if (
            val.rddStatus === "2" ||
            (val.rddStatus === "1" && val.updateType === "2")
          ) {
            conut++;
          }
        }
        a = `配送商${conut}`;
      }
      return a;
    };

    onMounted((_) => {
      handlList();
      handlProductData();
    });

    return {
      ...toRefs(data),
      aloneClick,
      cellStyle,
      handlSet,
      handlList,
      handlDele,
      handlEdit,
      distributeSuccsess,
      handlCalculate,
      handlFailure,
      handlProductData,
      filterDataConfirm,
      filterReset,
      handlChangeProduct,
    };
  },
};
</script>

<style scoped>
:deep(.el-button--text) {
  padding: 0;
  border: 0;
}
</style>
